using System;
using System.Threading.Tasks;
using System.Windows.Input;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using Prism.Commands;
using Prism.Mvvm;
using System.Windows.Forms;
using System.ComponentModel;

namespace CPlatePrintSys.Win.ViewModels
{
    public class InterfaceConfigViewModel : BindableBase
    {
        private readonly IGlobalConfigService _configService;

        // 接口配置属性
        private string _cadWinSharePath = @"\\192.168.2.3\CADWin\";
        public string CadWinSharePath
        {
            get => _cadWinSharePath;
            set => SetProperty(ref _cadWinSharePath, value);
        }

        private string _kmacsHttpMethod = "GET";
        public string KmacsHttpMethod
        {
            get => _kmacsHttpMethod;
            set 
            {
                var oldValue = _kmacsHttpMethod;
                SetProperty(ref _kmacsHttpMethod, value);
                System.Diagnostics.Debug.WriteLine($"KmacsHttpMethod changed from '{oldValue}' to '{value}'");
            }
        }

        private string _kmacsApiUrl = "http://192.168.1.0/biz/getInfo";
        public string KmacsApiUrl
        {
            get => _kmacsApiUrl;
            set => SetProperty(ref _kmacsApiUrl, value);
        }

        private int _timeoutSeconds = 30;
        public int TimeoutSeconds
        {
            get => _timeoutSeconds;
            set => SetProperty(ref _timeoutSeconds, value);
        }

        private bool _enableCache = true;
        public bool EnableCache
        {
            get => _enableCache;
            set => SetProperty(ref _enableCache, value);
        }

        private int _cacheExpirationMinutes = 10;
        public int CacheExpirationMinutes
        {
            get => _cacheExpirationMinutes;
            set => SetProperty(ref _cacheExpirationMinutes, value);
        }

        // 状态
        private string _statusMessage;
        public string StatusMessage
        {
            get { return _statusMessage; }
            set { SetProperty(ref _statusMessage, value); }
        }

        // 命令
        public ICommand SaveInterfaceConfigCommand { get; }
        public ICommand SelectCadWinDirectoryCommand { get; }

        public InterfaceConfigViewModel(IGlobalConfigService configService)
        {
            _configService = configService;

            SaveInterfaceConfigCommand = new DelegateCommand(async () => await SaveInterfaceConfig());
            SelectCadWinDirectoryCommand = new DelegateCommand(SelectCadWinDirectory);

            // 确保有默认值
            KmacsHttpMethod = "GET";
            
            LoadConfig();
        }

        private async void LoadConfig()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("LoadConfig: Starting to load configuration...");
                var config = await _configService.GetInterfaceConfigAsync();
                if (config != null)
                {
                    System.Diagnostics.Debug.WriteLine($"LoadConfig: Config loaded, KmacsHttpMethod from DB: '{config.KmacsHttpMethod}'");
                    
                    // 将模型数据映射到ViewModel属性
                    CadWinSharePath = config.CadWinSharePath;
                    KmacsApiUrl = config.KmacsApiUrl;
                    TimeoutSeconds = config.TimeoutSeconds;
                    EnableCache = config.EnableCache;
                    CacheExpirationMinutes = config.CacheExpirationMinutes;
                    
                    // 确保HTTP方法有有效值
                    var httpMethod = config.KmacsHttpMethod;
                    if (string.IsNullOrEmpty(httpMethod) || 
                        (httpMethod != "GET" && httpMethod != "POST" && httpMethod != "PUT" && httpMethod != "DELETE"))
                    {
                        System.Diagnostics.Debug.WriteLine($"LoadConfig: Invalid HTTP method '{httpMethod}', using default 'GET'");
                        httpMethod = "GET";
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"LoadConfig: Using HTTP method '{httpMethod}'");
                    }
                    KmacsHttpMethod = httpMethod;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("LoadConfig: No config found, using default 'GET'");
                    // 如果没有配置，使用默认值
                    KmacsHttpMethod = "GET";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"LoadConfig: Exception occurred: {ex.Message}");
                // 使用默认配置
                KmacsHttpMethod = "GET";
            }
        }

        private async Task SaveInterfaceConfig()
        {
            try
            {
                StatusMessage = "正在保存配置...";
                
                // 将ViewModel数据映射到模型
                var config = new InterfaceConfig
                {
                    CadWinSharePath = CadWinSharePath,
                    KmacsHttpMethod = KmacsHttpMethod,
                    KmacsApiUrl = KmacsApiUrl,
                    TimeoutSeconds = TimeoutSeconds,
                    EnableCache = EnableCache,
                    CacheExpirationMinutes = CacheExpirationMinutes
                };

                await _configService.UpdateInterfaceConfigAsync(config, "System");
                StatusMessage = "配置保存成功";
                
                // 3秒后清除状态消息
                await Task.Delay(1500);
                StatusMessage = "";
            }
            catch (Exception ex)
            {
                StatusMessage = $"保存失败: {ex.Message}";
            }
        }

        private void SelectCadWinDirectory()
        {
            try
            {
                var dialog = new System.Windows.Forms.FolderBrowserDialog
                {
                    Description = "选择CADWin共享目录",
                    ShowNewFolderButton = false
                };

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    CadWinSharePath = dialog.SelectedPath;
                    StatusMessage = "目录已选择";
                    
                    // 2秒后清除状态消息
                    Task.Delay(1000).ContinueWith(_ => 
                    {
                        StatusMessage = "";
                    });
                }
            }
            catch (Exception ex)
            {
                StatusMessage = $"选择目录失败: {ex.Message}";
            }
        }
    }
} 